<template>
  <view class="set-push-container">
    <!-- 顶部说明卡片 -->
    <view class="header-card">
      <view class="header-icon">
        <uv-icon name="bell" size="40" color="#fff"></uv-icon>
      </view>
      <view class="header-content">
        <text class="header-title">订阅提醒设置</text>
        <text class="header-desc">管理您的推送通知偏好</text>
      </view>
    </view>

    <!-- 策略设置 - 跳转项 -->
    <view class="section-title">
      <text>推送管理</text>
    </view>
    <view class="setting-card">
      <view class="setting-item clickable" @click="goToStrategySettings">
        <view class="item-left">
          <view class="item-icon strategy-icon">
            <uv-icon name="setting" size="36" color="#06CBB6"></uv-icon>
          </view>
          <view class="item-content">
            <text class="item-label">策略设置</text>
            <text class="item-desc">配置推送策略和周期</text>
          </view>
        </view>
        <view class="item-right">
          <uv-icon name="arrow-right" size="32" color="#C5C5C5"></uv-icon>
        </view>
      </view>
    </view>

    <!-- 推送方式设置 -->
    <!-- <view class="section-title">
      <text>推送方式</text>
    </view> -->
    <view class="setting-card">
      <!-- <view class="setting-item">
        <view class="item-left">
          <view class="item-icon sms-icon">
            <uv-icon name="chat" size="36" color="#FF9500"></uv-icon>
          </view>
          <view class="item-content">
            <text class="item-label">短信提醒</text>
            <text class="item-desc">通过短信接收推送通知</text>
          </view>
        </view>
        <view class="item-right">
          <switch
            :checked="smsNotification"
            @change="onSmsChange"
            color="#06CBB6"
          />
        </view>
      </view> -->

      <view class="setting-item last-item" v-if="showStrategyEmail">
        <view class="item-left">
          <view class="item-icon email-icon">
            <uv-icon name="email" size="36" color="#3498DB"></uv-icon>
          </view>
          <view class="item-content">
            <text class="item-label">邮箱提醒</text>
            <text class="item-desc">通过邮箱接收推送通知</text>
          </view>
        </view>
        <view class="item-right">
          <switch
            :checked="emailNotification"
            @change="onEmailChange"
            color="#06CBB6"
          />
        </view>
      </view>
    </view>

    <!-- 推送开关设置 -->
    <view class="section-title">
      <text>数据订阅</text>
    </view>
    <view class="setting-card">
      <view class="setting-item">
        <view class="item-left">
          <view class="item-icon news-icon">
            <uv-icon name="file-text" size="36" color="#FF6B6B"></uv-icon>
          </view>
          <view class="item-content">
            <text class="item-label">新闻快讯</text>
            <text class="item-desc">实时财经新闻推送</text>
          </view>
        </view>
        <view class="item-right">
          <switch
            :checked="pushSettings.newsFlash"
            @change="handleSwitchChange('newsFlash', $event)"
            color="#06CBB6"
          /> 
        </view>
      </view>
      <view class="setting-item">
        <view class="item-left">
          <view class="item-icon ai-icon">
            <uv-icon name="chat" size="36" color="#8B5CF6"></uv-icon>
          </view> 
          <view class="item-content">
            <text class="item-label">AI小智</text>
            <text class="item-desc">AI定时分析-小智AI</text>
          </view>
        </view>
        <view class="item-right">
          <switch
            :checked="pushSettings.aiAnalyze"
            @change="handleSwitchChange('aiAnalyze', $event)"
            color="#06CBB6"
          />
        </view>
      </view>
 
      <view class="setting-item">
        <view class="item-left">
          <view class="item-icon calendar-icon">
            <uv-icon name="clock" size="36" color="#4ECDC4"></uv-icon>
          </view>
          <view class="item-content">
            <text class="item-label">日历</text>
            <text class="item-desc">重要事件日历提醒</text>
          </view>
        </view>
        <view class="item-right">
          <switch
            :checked="pushSettings.calendar"
            @change="handleSwitchChange('calendar', $event)"
            color="#06CBB6"
          />
        </view>
      </view>

      <view class="setting-item last-item">
        <view class="item-left">
          <view class="item-icon chain-icon">
            <uv-icon name="search" size="36" color="#9B59B6"></uv-icon>
          </view>
          <view class="item-content">
            <text class="item-label">大额转账</text>
            <text class="item-desc">大额转账提醒</text>
          </view>
        </view>
        <view class="item-right">
          <switch
            :checked="pushSettings.chainExplorer"
            @change="handleSwitchChange('chainExplorer', $event)"
            color="#06CBB6"
          />
        </view>
      </view>
    </view>

    <!-- 温馨提示 -->
    <view class="tip-card">
      <view class="tip-icon">
        <uv-icon name="info-circle" size="32" color="#06CBB6"></uv-icon>
      </view>
      <text class="tip-text">开启订阅后，您将及时收到相关数据的推送通知</text>
    </view>

    <!-- 邮箱输入弹窗 -->
    <email-input-popup
      ref="emailPopup"
      @confirm="onEmailConfirm"
      @cancel="onEmailCancel"
    ></email-input-popup>
  </view>
</template>

<script>
import { setUniPushSetting, getUniPushSettingList, updateUserInfo } from '@/api/user'
import { setStrategyPushType, getStrategyPushType } from '@/api/tactics'
import { mapState } from 'vuex'
import EmailInputPopup from '@/components/email-input-popup/email-input-popup.vue'

/**
 * 订阅提醒设置页面
 * @description 管理用户的推送订阅设置，包括策略设置入口和各类推送开关
 */
export default {
  name: 'SetPush',

  components: {
    EmailInputPopup
  },

  data() {
    return {
      /**
       * 推送设置数据
       * @property {boolean} newsFlash - 新闻快讯推送开关 (对应接口类型: news)
       * @property {boolean} calendar - 日历推送开关 (对应接口类型: economicData)
       * @property {boolean} chainExplorer - 链上侦探推送开关 (对应接口类型: whaleTransfer)
       */
      pushSettings: {
        newsFlash: true,      // 新闻快讯 -> news
        calendar: true,       // 日历 -> economicData
        chainExplorer: true,   // 链上侦探 -> whaleTransfer
        aiAnalyze: true
      },
      // 推送类型映射：页面key -> 接口type
      pushTypeMap: {
        newsFlash: 'news',           // 快讯
        calendar: 'economicData',    // 财经日历
        chainExplorer: 'whaleTransfer', // 大额转账
        aiAnalyze: 'aiAnalyze'
      },
      // 正在保存的状态，防止重复提交
      saving: false,

      // 短信和邮箱提醒
        smsNotification: false,
        emailNotification: false,
        userEmail: '', // 用户已保存的邮箱
        showStrategyEmail: false, // 是否显示邮箱开关，默认关闭
    }
  },

  computed: {
    ...mapState('user', ['email'])
  },

  /**
   * 页面加载时执行
   */
  onLoad() {
    // 先从接口获取推送设置
    this.loadPushSettingsFromApi()
    // 获取用户邮箱
    this.getUserEmail()
    // 获取短信和邮箱推送状态
    this.loadNotificationSettings()
  },

  methods: {
    /**
     * 从接口加载推送设置
     * @description 从服务器获取用户的推送设置，并更新页面状态
     */
    async loadPushSettingsFromApi() {
      try {
        uni.showLoading({ title: '加载中...', mask: false })
        
        const res = await getUniPushSettingList()
        console.log('推送设置列表:', res)
        
        if (res.code === 200 && res.data && Array.isArray(res.data)) {
          // 将接口返回的数据映射到页面设置
          // 接口返回的是数组，需要根据 type 字段映射到对应的页面 key
          const typeToKeyMap = {
            'news': 'newsFlash',           // 快讯 -> 新闻快讯
            'economicData': 'calendar',    // 财经日历 -> 日历
            'whaleTransfer': 'chainExplorer',  // 大额转账 -> 链上侦探
            'aiAnalyze': 'aiAnalyze'
          }

          // 初始化所有设置为 false
          this.pushSettings = {
            newsFlash: false,
            calendar: false,
            chainExplorer: false,
            aiAnalyze: false
          }
          
          // 根据接口返回的数据更新设置
          res.data.forEach(item => {
            const key = typeToKeyMap[item.type]
            console.log(key);
            
            if (key) {
              this.pushSettings[key] = item.enable || false
            }
          })
          // 保存到本地存储作为缓存
          this.savePushSettingsToLocal()
          
          console.log('更新后的推送设置:', this.pushSettings)
        } else {
          console.warn('推送设置数据格式不正确，使用默认值')
          // 如果接口返回数据格式不正确，尝试从本地存储加载
          this.loadPushSettingsFromLocal()
        }
      } catch (error) {
        console.error('获取推送设置失败:', error)
        // 接口失败时，从本地存储加载
        this.loadPushSettingsFromLocal()
        uni.showToast({
          title: '加载设置失败，使用本地缓存',
          icon: 'none',
          duration: 2000
        })
      } finally {
        uni.hideLoading()
      }
    },

    /**
     * 从本地存储加载推送设置
     * @description 从本地存储中读取用户之前保存的推送设置（作为备用方案）
     */
    loadPushSettingsFromLocal() {
      try {
        const savedSettings = uni.getStorageSync('push_settings')
        if (savedSettings) {
          this.pushSettings = JSON.parse(savedSettings)
        } else {
          // 如果本地也没有数据，使用默认值
          this.pushSettings = {
            newsFlash: false,
            calendar: false,
            chainExplorer: false,
            aiAnalyze: false
          }
        }
      } catch (error) {
        console.error('加载本地推送设置失败:', error)
        // 出错时使用默认值
        this.pushSettings = {
          newsFlash: false,
          calendar: false,
          chainExplorer: false,
          aiAnalyze: false
        }
      }
    },

    /**
     * 保存推送设置到本地存储
     * @description 将当前的推送设置保存到本地存储（作为缓存）
     */
    savePushSettingsToLocal() {
      try {
        uni.setStorageSync('push_settings', JSON.stringify(this.pushSettings))
      } catch (error) {
        console.error('保存推送设置到本地失败:', error)
      }
    },

    /**
     * 处理开关状态变化
     * @param {string} key - 设置项的键名 (newsFlash/calendar/chainExplorer)
     * @param {Event} event - 开关变化事件
     */
    async handleSwitchChange(key, event) {
      const newValue = event.detail.value
      const oldValue = this.pushSettings[key]
      
      // 先更新本地状态（乐观更新）
      this.pushSettings[key] = newValue
      this.savePushSettingsToLocal()
      
      // 获取对应的接口类型
      const pushType = this.pushTypeMap[key]
      if (!pushType) {
        console.error('未知的推送类型:', key)
        // 回滚状态
        this.pushSettings[key] = oldValue
        return
      }
      
      // 防止重复提交
      if (this.saving) {
        return
      }
      
      this.saving = true
      
      try {
        // 调用接口更新推送设置
        const res = await setUniPushSetting({
          type: pushType,
          enable: newValue
        })
        
        if (res.code === 200) {
          // 显示提示
          const labels = {
            newsFlash: '快讯',
            calendar: '财经日历',
            chainExplorer: '大额转账',
            aiAnalyze: 'AI小智'
          }
          
          uni.showToast({
            title: `${labels[key]}推送已${newValue ? '开启' : '关闭'}`,
            icon: 'none',
            duration: 1500
          })
        } else {
          // 接口返回错误，回滚状态
          this.pushSettings[key] = oldValue
          this.savePushSettingsToLocal()
          uni.showToast({
            title: res.message || '设置失败，请重试',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('更新推送设置失败:', error)
        // 请求失败，回滚状态
        this.pushSettings[key] = oldValue
        this.savePushSettingsToLocal()
        uni.showToast({
          title: error.message || '网络错误，请重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.saving = false
      }
    },

    /**
     * 跳转到策略设置页面
     * @description 导航到策略详细设置页面
     */
    goToStrategySettings() {
      uni.navigateTo({
        url: '/subPages/push/setting'
      })
    },

    /**
     * 获取用户邮箱
     */
    async getUserEmail() {
      try {
        // 先从 Vuex 获取
        if (this.email) {
          this.userEmail = this.email
          console.log('从 Vuex 获取邮箱:', this.userEmail)
          return
        }

        // 如果 Vuex 没有，从 store 获取
        const storeEmail = this.$store.state.user.userMsg.email
        if (storeEmail) {
          this.userEmail = storeEmail
          console.log('从 store 获取邮箱:', this.userEmail)
          return
        }

        // 如果 store 也没有，调用 store action 获取最新数据
        await this.$store.dispatch('user/getUserMsg')
        this.userEmail = this.$store.state.user.userMsg.email || ''
        console.log('从接口获取邮箱:', this.userEmail)
      } catch (error) {
        console.error('获取用户邮箱失败:', error)
      }
    },

    /**
     * 加载短信和邮箱推送状态
     */
    async loadNotificationSettings() {
      try {
        // 从接口获取策略推送类型配置
        const res = await getStrategyPushType()
        console.log('策略推送类型配置:', res)

        if (res.code === 200 && res.data) {
            // 根据接口返回的数据更新状态
          this.showStrategyEmail = res.data.showStrategyEmail || false
          this.smsNotification = res.data.strategySmsPush || false
          this.emailNotification = res.data.strategyEmailPush || false

          // 保存到本地存储作为缓存
          uni.setStorageSync('sms_notification', this.smsNotification)
          uni.setStorageSync('email_notification', this.emailNotification)
        }
      } catch (error) {
        console.error('加载通知设置失败:', error)
        // 失败时从本地存储加载
        const smsStatus = uni.getStorageSync('sms_notification')
        const emailStatus = uni.getStorageSync('email_notification')

        if (smsStatus !== undefined && smsStatus !== '') {
          this.smsNotification = smsStatus === 'true' || smsStatus === true
        }
        if (emailStatus !== undefined && emailStatus !== '') {
          this.emailNotification = emailStatus === 'true' || emailStatus === true
        }
      }
    },

    /**
     * 短信提醒开关变更
     */
    async onSmsChange(event) {
      const value = event.detail.value
      console.log('短信提醒开关变更:', value)

      try {
        uni.showLoading({ title: '处理中...', mask: true })

        // 调用设置策略推送类型接口
        const res = await setStrategyPushType({
          type: 'sms',
          enable: value
        })

        uni.hideLoading()

        if (res.code === 200) {
          this.smsNotification = value
          // 保存到本地存储
          uni.setStorageSync('sms_notification', value)
          uni.showToast({
            title: value ? '已开启短信提醒' : '已关闭短信提醒',
            icon: 'none',
            duration: 2000
          })
        } else {
          throw new Error(res.message || '操作失败')
        }
      } catch (error) {
        console.error('设置短信提醒失败:', error)
        this.smsNotification = !value // 恢复开关状态
        uni.hideLoading()
        uni.showToast({
          title: error.message || '操作失败，请重试',
          icon: 'none'
        })
      }
    },

    /**
     * 邮箱提醒开关变更
     */
    async onEmailChange(event) {
      const value = event.detail.value
      console.log('邮箱提醒开关变更:', value)

      if (!value) {
        // 关闭邮箱提醒
        try {
          uni.showLoading({ title: '处理中...', mask: true })

          // 调用设置策略推送类型接口
          const res = await setStrategyPushType({
            type: 'email',
            enable: false
          })

          uni.hideLoading()

          if (res.code === 200) {
            this.emailNotification = false
            // 保存到本地存储
            uni.setStorageSync('email_notification', false)
            uni.showToast({
              title: '已关闭邮箱提醒',
              icon: 'none',
              duration: 2000
            })
          } else {
            throw new Error(res.message || '操作失败')
          }
        } catch (error) {
          console.error('关闭邮箱提醒失败:', error)
          this.emailNotification = true // 恢复开关状态
          uni.hideLoading()
          uni.showToast({
            title: error.message || '操作失败，请重试',
            icon: 'none'
          })
        }
      } else {
        // 开启邮箱提醒
        // 检查用户是否已有邮箱
        if (this.userEmail) {
          // 用户已有邮箱，直接开启
          try {
            uni.showLoading({ title: '处理中...', mask: true })

            // 调用设置策略推送类型接口
            const res = await setStrategyPushType({
              type: 'email',
              enable: true
            })

            uni.hideLoading()

            if (res.code === 200) {
              this.emailNotification = true
              // 保存到本地存储
              uni.setStorageSync('email_notification', true)
              uni.showToast({
                title: '已开启邮箱提醒',
                icon: 'none',
                duration: 2000
              })
            } else {
              throw new Error(res.message || '操作失败')
            }
          } catch (error) {
            console.error('开启邮箱提醒失败:', error)
            this.emailNotification = false // 恢复开关状态
            uni.hideLoading()
            uni.showToast({
              title: error.message || '操作失败，请重试',
              icon: 'none'
            })
          }
        } else {
          // 用户没有邮箱，打开弹窗输入
          this.$refs.emailPopup.open()
        }
      }
    },

    /**
     * 邮箱输入弹窗确认
     */
    async onEmailConfirm(email) {
      console.log('确认输入邮箱:', email)
      // 保存邮箱到服务器
      await this.saveEmailToServer(email)
    },

    /**
     * 邮箱输入弹窗取消
     */
    onEmailCancel() {
      console.log('取消输入邮箱')
      // 关闭开关
      this.emailNotification = false
    },

    /**
     * 保存邮箱到服务器
     */
    async saveEmailToServer(email) {
      try {
        uni.showLoading({ title: '保存中...', mask: true })

        // 第一步：更新用户邮箱信息
        const updateRes = await updateUserInfo({ email })

        if (updateRes.code !== 200) {
          throw new Error(updateRes.message || '保存邮箱失败')
        }

        // 第二步：开启邮箱推送
        const pushRes = await setStrategyPushType({
          type: 'email',
          enable: true
        })

        uni.hideLoading()

        if (pushRes.code === 200) {
          // 保存成功
          this.userEmail = email
          this.emailNotification = true
          // 保存到本地存储
          uni.setStorageSync('email_notification', true)

          // 更新 Vuex
          this.$store.commit('user/SET_USER_DATA', { email })

          uni.showToast({
            title: '邮箱已保存并开启提醒',
            icon: 'success',
            duration: 2000
          })
        } else {
          throw new Error(pushRes.message || '开启邮箱提醒失败')
        }
      } catch (error) {
        console.error('保存邮箱失败:', error)
        uni.hideLoading()

        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })

        // 关闭开关
        this.emailNotification = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.set-push-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #F8F9FA 0%, #FFFFFF 100%);
  padding: 32rpx;
}

/* 顶部卡片 */
.header-card {
  display: flex;
  align-items: center;
  padding: 32rpx;
  margin-bottom: 32rpx;
  background: linear-gradient(135deg, #06CBB6 0%, #04A89E 100%);
  border-radius: 24rpx;
}

.header-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80rpx;
  height: 80rpx;
  margin-right: 24rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
}

.header-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.header-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #fff;
  margin-bottom: 8rpx;
}

.header-desc {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
}

/* 分组标题 */
.section-title {
  padding: 0 8rpx 16rpx;
  
  text {
    font-size: 28rpx;
    font-weight: 600;
    color: #666;
  }
}

/* 设置卡片 */
.setting-card {
  background: #fff;
  border-radius: 20rpx;
  margin-bottom: 32rpx;
  overflow: hidden;
}

/* 设置项 */
.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #F5F5F5;
  transition: background-color 0.3s ease;
  
  &.last-item {
    border-bottom: none;
  }
  
  &.clickable {
    cursor: pointer;
    
    &:active {
      background-color: #F8F9FA;
      transform: scale(0.99);
    }
  }
}

.item-left {
  flex: 1;
  display: flex;
  align-items: center;
}

.item-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 72rpx;
  height: 72rpx;
  margin-right: 24rpx;
  border-radius: 16rpx;
  flex-shrink: 0;
  
  &.strategy-icon {
    background: linear-gradient(135deg, rgba(6, 203, 182, 0.1) 0%, rgba(6, 203, 182, 0.05) 100%);
  }

  &.sms-icon {
    background: linear-gradient(135deg, rgba(255, 149, 0, 0.1) 0%, rgba(255, 149, 0, 0.05) 100%);
  }

  &.email-icon {
    background: linear-gradient(135deg, rgba(52, 152, 219, 0.1) 0%, rgba(52, 152, 219, 0.05) 100%);
  }

  &.news-icon {
    background: linear-gradient(135deg, rgba(255, 107, 107, 0.1) 0%, rgba(255, 107, 107, 0.05) 100%);
  }

  &.ai-icon {
    background: linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(139, 92, 246, 0.05) 100%);
  }

  &.calendar-icon {
    background: linear-gradient(135deg, rgba(78, 205, 196, 0.1) 0%, rgba(78, 205, 196, 0.05) 100%);
  }

  &.chain-icon {
    background: linear-gradient(135deg, rgba(155, 89, 182, 0.1) 0%, rgba(155, 89, 182, 0.05) 100%);
  }
}

.item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.item-label {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 6rpx;
}

.item-desc {
  font-size: 24rpx;
  color: #999;
}

.item-right {
  display: flex;
  align-items: center;
  margin-left: 16rpx;
}

/* 温馨提示卡片 */
.tip-card {
  display: flex;
  align-items: flex-start;
  padding: 24rpx;
  background: linear-gradient(135deg, #F8F9FA 0%, #FFFFFF 100%);
  border-radius: 16rpx;
  border-left: 6rpx solid #06CBB6;
}

.tip-icon {
  display: flex;
  align-items: center;
  margin-right: 16rpx;
  margin-top: 4rpx;
}

.tip-text {
  flex: 1;
  font-size: 24rpx;
  line-height: 1.8;
  color: #666;
}
</style>
